from rest_framework import serializers
from django.core.validators import FileExtensionValidator


class UploadImageSerializer(serializers.Serializer):
    #ImageField会校验是否是图片 .png  .jpg .jpeg .gif
    image = serializers.ImageField(
        validators=[FileExtensionValidator(allowed_extensions=['png', 'jpg', 'jpeg', 'gif'])],
        error_messages={
            'required': '请上传图片文件',
            'invalid_extension': '请上传图片文件'
        }
    )
    def validate_image(self, value):
        #  图片大小单位是字节
        max_size = 100 * 1024 * 1024
        size = value.size
        if size > max_size:
            raise serializers.ValidationError('图片大小不能超过100mb')
        return value